package com.caigou.modules.forum.ui.publish

import android.os.Bundle
import android.text.TextUtils
import android.util.TypedValue
import android.view.View
import android.widget.ImageView
import androidx.activity.viewModels
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.bus.BusKey
import com.caigou.comm.base.bus.LiveDataBus
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseActivity
import com.caigou.comm.base.ext.*
import com.caigou.comm.base.utils.GlideEngine
import com.caigou.modules.forum.R
import com.caigou.modules.forum.bean.FifaItemBean
import com.caigou.modules.forum.bean.MarketItemBean
import com.caigou.modules.forum.databinding.ActivityPublishPostBinding
import com.caigou.modules.forum.viewmodel.PublishViewModel
import com.caigou.modules.forum.widget.ContestTypeDialog
import com.caigou.modules.forum.widget.FifaTypeDialog
import com.caigou.modules.forum.widget.MarketTypeDialog
import com.caigou.modules.forum.widget.PacketPublishDialog
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.listener.OnResultCallbackListener
import com.lwkandroid.widget.ngv.DefaultNgvAdapter
import com.lwkandroid.widget.ngv.NgvChildImageView
import dagger.hilt.android.AndroidEntryPoint
import org.json.JSONObject
import java.io.File

/**
 * @author #Suyghur.
 * Created on 2021/12/21
 */
@Route(path = RouterPath.Forum.PAGE_PUBLISH_POST)
@AndroidEntryPoint
class PublishPostActivity : BaseActivity() {

    private lateinit var binding: ActivityPublishPostBinding
    private val publishViewModel: PublishViewModel by viewModels()

    @JvmField
    @Autowired(name = AppConstants.FORUM_TYPE)
    var forumType: Int = 0

    private var dareContent = ""
    private var dareType = -1
    private var fifaTypeId = -1
    private var marketTypeId = -1

    var redPacketCount = 0
    var redPacketMoney = 0.00f

    private val picUrls = mutableListOf<String>()
    private val fifaTypes = mutableListOf<FifaItemBean>()
    private val marketTypes = mutableListOf(
        MarketItemBean(0, "特码"),
        MarketItemBean(1, "平肖"),
        MarketItemBean(2, "生肖"),
        MarketItemBean(3, "综合"),
        MarketItemBean(4, "头数"),
        MarketItemBean(5, "尾数"),
        MarketItemBean(6, "大小单双"),
        MarketItemBean(7, "波色"),
        MarketItemBean(8, "五行"),
        MarketItemBean(9, "家野"),
        MarketItemBean(10, "杀码"),
        MarketItemBean(11, "合数"),
        MarketItemBean(12, "统计数"),
        MarketItemBean(13, "码段")
    )

    private val picAdapter: DefaultNgvAdapter<String> by lazy {
        DefaultNgvAdapter(100, GlideDisplay())
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPublishPostBinding.inflate(layoutInflater)
        setContentView(binding.root)
        containerId = binding.publishPostLlContainer.id
        initView()
    }

    private fun initView() {
        ARouter.getInstance().inject(this)

        binding.publishPostTvTitle.text = when (forumType) {
            1 -> "港彩发布"
            2 -> "澳彩发布"
            3 -> "新加坡彩发布"
            4 -> "台湾彩发布"
            5 -> "足球论坛发布"
            6 -> "猛料市场发布"
            else -> "发布帖子"
        }

        publishViewModel.getFifaTypeList()

        binding.publishPostNgvPic.setSingleImageSize(TypedValue.COMPLEX_UNIT_DIP, 150, 150)
        picAdapter.setOnChildClickListener(object : DefaultNgvAdapter.OnChildClickedListener<String> {
            override fun onPlusImageClicked(plusImageView: ImageView?, dValueToLimited: Int) {
                openGallery()
            }

            override fun onContentImageClicked(position: Int, data: String?, childImageView: NgvChildImageView?) {
                data?.apply {
                    showImgsPreview(this@PublishPostActivity, picUrls, picUrls.indexOf(this))
                }
            }

            override fun onImageDeleted(position: Int, data: String?) {
                data?.apply {
                }
            }
        })
        binding.publishPostNgvPic.adapter = picAdapter

        binding.publishPostTvHistory.setOnClickListener {
            ARouter.getInstance().build(RouterPath.Forum.PAGE_FORUM_HISTORY_POST)
                .withInt(AppConstants.FORUM_TYPE, forumType)
                .withString(AppConstants.USER_ID, AppBackgroundInfo.instance.userBean!!.userId)
                .navigation()
        }

        binding.publishPostTvPacket.setOnClickListener {
            with(PacketPublishDialog(this)) {
                btnConfirm.setOnClickListener {
                    if (packetMoney < 10f || packetMoney > 500f) {
                        showToast("发红包总金额最少10.元，最多100.0元")
                        return@setOnClickListener
                    }
                    if (packetCount < 100 || packetCount > 300) {
                        showToast("每次最少可发100个随机红包，最多可发999个随机红包")
                        return@setOnClickListener
                    }
                    binding.publishPostTvPacket.text = "${packetMoney}元"
                    this@PublishPostActivity.redPacketMoney = packetMoney
                    this@PublishPostActivity.redPacketCount = packetCount
                    dismiss()
                }
                show()
            }
        }

        binding.publishPostTvAssistant.setOnClickListener {
            ARouter.getInstance().build(RouterPath.Query.PAGE_ASSISTANT).navigation()
        }

        binding.publishPostTvContest.visibility = if (forumType == 1 || forumType == 2 || forumType == 5 || forumType == 6) {
            View.VISIBLE
        } else {
            View.GONE
        }

        binding.publishPostTvContest.setOnClickListener {
            when (forumType) {
                1, 2 -> ContestTypeDialog(this, forumType).show()
                5 -> {
                    with(FifaTypeDialog(this, fifaTypes)) {
                        btnConfirm.setOnClickListener {
                            val bean = mAdapter.getItem(mAdapter.checkPos)
                            binding.publishPostTvContest.text = bean.fifaTypeName
                            fifaTypeId = bean.fifaTypeId
                            dismiss()
                        }
                        show()
                    }
                }
                6 -> {
                    with(MarketTypeDialog(this, marketTypes)) {
                        btnConfirm.setOnClickListener {
                            val bean = mAdapter.getItem(mAdapter.checkPos)
                            binding.publishPostTvContest.text = bean.marketTypeName
                            marketTypeId = bean.marketTypeId
                            dismiss()
                        }
                        show()
                    }
                }
            }
        }

        binding.publishContestTvClear.setOnClickListener {
            binding.publishContestLlTips.visibility = View.GONE
            dareType = -1
            dareContent = ""
            binding.publishPostTvContest.text = "我要参赛"
        }

        binding.publishPostBtnSubmit.setOnClickListener {
            it.hideKeyboard()
            val title = binding.publishPostEtTitle.text.toString()
            val content = binding.publishPostEtContent.text.toString()
            if (TextUtils.isEmpty(title)) {
                showToast("标题不能为空！")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(content)) {
                showToast("内容不能为空！")
                return@setOnClickListener
            }
            val files = mutableListOf<File>()
            picUrls.forEach {
                files.add(File(it))
            }

            when (forumType) {
                1, 2 -> {
                    if (TextUtils.isEmpty(dareContent)) {
                        publishViewModel.publishPost(
                            files, title, content,
                            AppBackgroundInfo.instance.userBean!!.userId,
                            forumType, redPacketMoney, redPacketCount
                        )
                    } else {
                        publishViewModel.publishContestPost(
                            files, title, content,
                            AppBackgroundInfo.instance.userBean!!.userId, forumType,
                            dareContent, dareType, redPacketMoney, redPacketCount
                        )
                    }
                }
                5 -> {
                    if (fifaTypeId == -1) {
                        showToast("请选择联赛类型！")
                        return@setOnClickListener
                    }
                    publishViewModel.publishFifaPost(
                        files, title, content,
                        AppBackgroundInfo.instance.userBean!!.userId,
                        forumType, fifaTypeId,
                        redPacketMoney, redPacketCount
                    )
                }
                6 -> {
                    if (marketTypeId == -1) {
                        showToast("请选择类型！")
                        return@setOnClickListener
                    }
                    publishViewModel.publishMarketPost(
                        files, title, content,
                        AppBackgroundInfo.instance.userBean!!.userId,
                        forumType, marketTypeId,
                        redPacketMoney, redPacketCount
                    )
                }
                else -> {
                    publishViewModel.publishPost(files, title, content, AppBackgroundInfo.instance.userBean!!.userId, forumType, redPacketMoney, redPacketCount)
                }
            }
        }

        binding.publishPostTvBack.setOnClickListener {
            it.hideKeyboard()
            finish()
        }

        LiveDataBus.get().with(BusKey.DARE_CONTENT_FILL, String::class.java).observe(this) {
            if (!TextUtils.isEmpty(it)) {
                val jsonObject = JSONObject(it)
                dareContent = jsonObject.getString("dareContent")
                dareType = jsonObject.getInt("dareType")
                binding.publishPostTvContest.text = dareTypeName(dareType)
                binding.publishContestLlTips.visibility = View.VISIBLE
                binding.publishContestTvType.text = dareTypeName(dareType)
            }
        }
    }


    override fun observeViewModel() {
        super.observeViewModel()
        observe(publishViewModel.publishPostLiveData, ::handlePublishPost)
        observe(publishViewModel.fifaTypeListLiveData, ::handleGetFifaTypeList)
    }

    private fun handlePublishPost(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("帖子发布失败，请稍后再试")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data != null) {
                    showToast(result.data!!)
                }
                this.finish()
            }
        }
    }

    private fun handleGetFifaTypeList(result: Resource<MutableList<FifaItemBean>>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                result.data?.apply {
                    fifaTypes.addAll(this)
                }
            }
        }
    }

    private fun openGallery() {
        PictureSelector.create(this)
            .openGallery(PictureMimeType.ofImage())
            .theme(R.style.picture_WeChat_style)
            .imageEngine(GlideEngine.instance)
            .imageSpanCount(4)
            .isReturnEmpty(true)
            .selectionMode(PictureConfig.MULTIPLE)
            .maxSelectNum(9)
            .isPreviewImage(true)
            .isCamera(true)
            .isZoomAnim(true)
            .setCameraImageFormat(PictureMimeType.PNG)
            .isEnableCrop(false)
            .isCompress(true)
            .compressQuality(80)
            .synOrAsy(false)
            .withAspectRatio(1, 1)
            .minimumCompressSize(100)
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: MutableList<LocalMedia>?) {
                    result?.apply {
                        picUrls.clear()
                        forEach {
                            picUrls.add(it.compressPath)
                        }
                        picAdapter.dataList = picUrls
                    }
                }

                override fun onCancel() {
                }

            })
    }
}